package com.xmb.wpclient.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmb.wpclient.config.DataBaseConfig;
import com.xmb.wpclient.constant.LayTableR;
import com.xmb.wpclient.constant.R;
import com.xmb.wpclient.entity.*;
import com.xmb.wpclient.service.*;
import com.xmb.wpclient.utils.DateUtil;
import com.xmb.wpclient.utils.HttpRequestUtils;
import com.xmb.wpclient.utils.MD5;
import com.xmb.wpclient.vo.ResultVO;
import com.xmb.wpclient.vo.VoucherDetailVO;
import com.xmb.wpclient.vo.VoucherMasterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

@Controller
@RequestMapping("/manage/database_config")
@Slf4j
public class DatabaseConfigController {

    @Autowired
    private IU8DatabaseConfigService iU8DatabaseConfigService;

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("connection", iU8DatabaseConfigService.list().get(0));
        return "database_config/index";
    }

    @PostMapping("/connection")
    @ResponseBody
    public R connection(U8DatabaseConfig u8DatabaseConfig) {
        try {
            // 加载MySQL驱动程序
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            // 创建连接
            String url = "jdbc:sqlserver://"+u8DatabaseConfig.getIp()+":"+u8DatabaseConfig.getPort()+";Databasename="+u8DatabaseConfig.getDataBase();
            String username = u8DatabaseConfig.getUser();
            String password = u8DatabaseConfig.getPassword();
            DataBaseConfig.connection = DriverManager.getConnection(url, username, password);
            U8DatabaseConfig config = iU8DatabaseConfigService.list().get(0);
            u8DatabaseConfig.setId(config.getId());
            iU8DatabaseConfigService.updateById(u8DatabaseConfig);
        }catch (Exception e){
            e.printStackTrace();
            log.error("账套数据库连接失败。");
            return R.error("账套数据库连接失败,请检查信息是否填正确");
        }
        log.info("账套已连接，当前账套："+u8DatabaseConfig.getDataBase());
        return R.ok("账套已连接，当前账套："+u8DatabaseConfig.getDataBase());
    }
}
